<?php

namespace admin\modules\pub\controllers;

use yii\web\Controller;

class FileController extends Controller
{
    public function actionThumb($src, $maxWidth = 400, $maxHeight = 400)
    {
        $info = parse_url($src);
        $path = $info['path'];
        if (substr($path, 0, 9) === '/storage/') {
            $_src = \Yii::getAlias('@storage_root').str_replace('/storage/', '/', $path);
            if (file_exists($_src)) {
                $src = $_src;
            }
        } elseif (substr($path, 0, 15) === '/static/images/') {
            $_src = \Yii::getAlias('@static_root').str_replace('/static/images/', '/images/', $path);
            if (file_exists($_src)) {
                $src = $_src;
            }
        }

        $info = pathinfo($src);
        $ext = $info['extension'];

        // 读取原始图片
        switch ($ext) {
            case "jpg":
            case "jpeg":
                $srcImg = imagecreatefromjpeg($src);
                break;
            case "png":
                $srcImg = imagecreatefrompng($src);
                break;
            case "webp":
                $srcImg = imagecreatefromwebp($src);
                break;
            case "bmp":
                $srcImg = imagecreatefrombmp($src);
                break;
            case "wbmp":
                $srcImg = imagecreatefromwbmp($src);
                break;
            case "gif":
                $srcImg = imagecreatefromgif($src);
                break;
            default:
                $src = \Yii::getAlias('@static_aburl/images/404.jpeg');
                header('Content-Type: image/jpeg');
                readfile($src);exit;
        }
        $mimeType = \Yii::$app->wMimeTypes->getMimeType($ext);
        header('Content-Type: '.$mimeType);

        // 缩略图最大宽度和高度
//        $maxWidth = 400;
//        $maxHeight = 400;

        // 计算缩略图大小
        $srcWidth = imagesx($srcImg);
        $srcHeight = imagesy($srcImg);
        $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight);
        $newWidth = round($srcWidth * $scale);
        $newHeight = round($srcHeight * $scale);

        // 创建新的图像资源
        $newImg = imagecreatetruecolor($newWidth, $newHeight);

        // 将原始图片复制到新的图像资源中，并缩小
        imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);

        // 保存新的图像资源
        imagejpeg($newImg);
        exit;
    }
}